//The MIT License
//
//Copyright (c) 2009 nodchip
//
//Permission is hereby granted, free of charge, to any person obtaining a copy
//of this software and associated documentation files (the "Software"), to deal
//in the Software without restriction, including without limitation the rights
//to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//copies of the Software, and to permit persons to whom the Software is
//furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in
//all copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//THE SOFTWARE.
package tv.dyndns.kishibe.server.handwriting;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
import java.util.zip.DeflaterOutputStream;
import java.util.zip.InflaterInputStream;

import tv.dyndns.kishibe.client.game.WidgetInputTegaki;

public class RecognizerSzkgngn implements Recognizer {
	private static class Result implements Comparable<Result> {
		char c;
		double distance;

		public Result(char c, double distance) {
			this.c = c;
			this.distance = distance;
		}

		@Override
		public int compareTo(Result o) {
			return (int) Math.signum(distance != o.distance ? distance - o.distance : c - o.c);
		}
	}

	private final StrokeTransformer strokeTransformer = new StrokeTransformer();
	private final Map<Character, double[][]> vectorData;
	private final Scaler scaler;
	private final Set<String> availableCharacters;

	public RecognizerSzkgngn(String filePath) {
		Map<Character, double[][]> vectorData = null;
		Scaler scaler = null;

		try {
			final ObjectInputStream objectInputStream = new ObjectInputStream(new InflaterInputStream(new BufferedInputStream(new FileInputStream(filePath))));
			scaler = (Scaler) objectInputStream.readObject();
			vectorData = (Map<Character, double[][]>) objectInputStream.readObject();
			objectInputStream.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

		this.vectorData = vectorData;
		this.scaler = scaler;
		availableCharacters = new HashSet<String>();
		for (char c : vectorData.keySet()) {
			availableCharacters.add("" + c);
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see tv.dyndns.kishibe.server.handwriting.Recognizer#recognize(double[][][])
	 */
	public String[] recognize(double[][][] inputStrokes) {
		StrokeTransformer.scale(inputStrokes);
		final double[] inputVector = strokeTransformer.transform(inputStrokes);
		scaler.scale(inputVector);

		List<Result> list = new ArrayList<Result>();

		for (Entry<Character, double[][]> entry : vectorData.entrySet()) {
			final char c = entry.getKey();

			for (double[] vector : entry.getValue()) {
				final int numberOfValues = Math.min(inputVector.length, vector.length);
				double sum2 = 0;
				for (int index = 0; index < numberOfValues; ++index) {
					final double r = inputVector[index] - vector[index];
					sum2 += r * r;
				}
				sum2 /= numberOfValues;

				// final double r = (double) inputVector.length / vector.length;
				// sum2 *= Math.max(r, 1.0 / r);

				list.add(new Result(c, sum2));
			}
		}

		Collections.sort(list);

		final List<String> result = new ArrayList<String>();
		for (int i = 0; i < WidgetInputTegaki.NUMBER_OF_CANDIDATE; ++i) {
			final char c = list.get(i).c;
			if (result.contains(c)) {
				continue;
			}

			result.add("" + c);
		}

		return result.toArray(new String[0]);
	}

	public static void main(String[] args) {
		final Scaler scaler = new Scaler();
		final Parser parser = new Parser(new File("/var/www/html/qmaclone/handwriting-ja.xml"));
		parser.run();

		final StrokeTransformer strokeTransformer = new StrokeTransformer();
		Map<Character, double[][]> vectorData = strokeTransformer.transform(parser.getData());

		scaler.setScale(vectorData);
		vectorData = scaler.scale(vectorData);

		try {
			ObjectOutputStream outputStream = new ObjectOutputStream(new DeflaterOutputStream(new BufferedOutputStream(new FileOutputStream("/var/www/html/qmaclone/handwriting-ja.dat"))));
			outputStream.writeObject(scaler);
			outputStream.writeObject(vectorData);
			outputStream.close();
		} catch (Exception e) {
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see tv.dyndns.kishibe.server.handwriting.Recognizer#getAvailableCharacters()
	 */
	public Set<String> getAvailableCharacters() {
		return availableCharacters;
	}
}
